<template>
  <section class="f-shopLevel">
    <div class="w-card my-content-box">
      <div class="title-box">
        <span class="title-text">服务政策列表</span>
        <div>
          <el-button type="primary" plain @click="openDialog(1)">+ 新增</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="selectionChange">
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="id" label="ID" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary" @click="openDialog(2,scope.row)">
                {{ scope.row.id || '' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="tagImg" label="标签图标" align="center">
            <template v-slot="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.tagImg" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                fit="cover" :preview-src-list="[scope.row.tagImg]" preview-teleported />
            </template>
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称" align="center">
            <template v-slot="scope">
              {{ scope.row.tagName || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="power" label="展现权重" align="center">
            <template v-slot="scope">
              {{ scope.row.power || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="contentImg" label="内容图片" align="center">
            <template v-slot="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.contentImg" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" fit="cover" :preview-src-list="[scope.row.contentImg]" preview-teleported />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link style="font-size:14px;" type="danger" @click="settingHandle('delete',scope.row)">
                  删除
                </el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <!-- <div class="footer_btn_box">
              <el-button :disabled="chooseList.length == 0" @click="settingHandle('delete')" type="danger" plain>删除</el-button>
            </div> -->
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 确认密码 -->
      <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogForm.title" width="600" :close-on-click-modal="false">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="tagImg" label="标签图标">
          <el-upload class="f-img-uploader" :action="uploadForm.action" :headers="uploadForm.headers" :data="uploadForm.data"
            :show-file-list="false" :on-success="uploadSuccess" @click="dialogForm.uploadType = 1">
            <img v-if="dialogForm.tagImg" :src="dialogForm.tagImg" class="f-img" />
            <el-icon v-else class="f-img-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item prop="tagName" label="标签名称">
          <el-input v-model="dialogForm.tagName" placeholder="请输入标签名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="power" label="展现权重">
          <el-input v-model="dialogForm.power" type="number" placeholder="标签由权重高到低轮播" />
        </el-form-item>
        <el-form-item prop="contentImg" label="内容图片">
          <el-upload class="f-img-uploader" :action="uploadForm.action" :headers="uploadForm.headers" :data="uploadForm.data"
            :show-file-list="false" :on-success="uploadSuccess" @click="dialogForm.uploadType = 2">
            <img v-if="dialogForm.contentImg" :src="dialogForm.contentImg" class="f-img" />
            <el-icon v-else class="f-img-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel()">取消</el-button>
          <el-button type="primary" @click="dialogSave()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </section>
</template>
  
  <script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad, getStore } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import ConfirmPass from '@/components/confirmPass.vue'
import api from './api'

export default {
  components: { ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const confirmPasswordRef = ref(null)
    const dialogFormRef = ref(null)

    const state = reactive({
      searchForm: {
        "orderBy": "id desc",
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      chooseList: [],
      selectData: {},

      dialogVisible: false,
      dialogForm: {},
      dialogRules: {
        contentImg: [
          { required: true, message: '请上传内容图片', trigger: 'blur' },
        ],
        tagImg: [
          { required: true, message: '请上传标签图标', trigger: 'blur' },
        ],
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
        ],
        power: [
          { required: true, message: '请输入展现权重', trigger: 'blur' },
        ],
      },

      uploadForm: {
        action: '/ums/file/upload/user/pub',
        headers: {
          Authorization: getStore('USER_AUTHOR_INRE').Authorization || `'','','',3,20,''`,
          Token: `Bearer ${window.localStorage.getItem("USER_TOKEN_INRE")}`,
          platformHeadType: 'rcmsPlatform'
        },
        data: {}
      },
    })

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "orderBy": "id desc",
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.policyList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function settingHandle(type, data) {
      let title = ""
      let msg = ''
      if (type == 'delete') {
        title = '删除提示'
        msg = `您确定要将所选的服务政策删除吗？`
      }
      // if (state.chooseList.length == 0) {
      //   return
      // }
      state.selectData = data
      confirmPasswordRef.value.dialogShow(title, msg, type)
    }

    const confirmSuccess = (type) => {
      if (type == 'delete') {
        let json = {
          id: state.selectData.id
        }
        api.policyDelete(json).then(res => {
          successDeal('操作成功！')
          getTableData()
        })
      }
    }

    function selectionChange(list) {
      state.chooseList = list
    }

    const openDialog = (type, data) => {
      if (type == 1) {
        state.dialogForm.title = '新增服务政策'
      } else if (type == 2) {
        state.dialogForm = data
        state.dialogForm.title = '修改服务政策'
      }
      state.dialogVisible = true
    }

    const dialogCancel = () => {
      state.dialogVisible = false
      state.dialogForm = {}
      dialogFormRef.value.resetFields()
    }

    const dialogSave = () => {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = JSON.parse(JSON.stringify(state.dialogForm))
          let apiName
          if (state.dialogForm.title == '新增服务政策') {
            apiName = 'policyAdd'
          } else if (state.dialogForm.title == '修改服务政策') {
            apiName = 'policyModify'
          }
          api[apiName](json).then(res => {
            successDeal('操作成功！')
            getTableData()
            dialogCancel()
          })
        }
      })
    }

    const selectDate = (e) => {
      state.searchForm.createTimeMin = e[0]
      state.searchForm.createTimeMax = e[1]
    }

    const uploadSuccess = (res) => {
      if (res.code == '200') {
        if (state.dialogForm.uploadType == 1) {
          state.dialogForm.tagImg = res.data.ossUrl
        } else {
          state.dialogForm.contentImg = res.data.ossUrl
        }
        dialogFormRef.value.validate()
      } else {
        errorDeal(res.msg)
      }
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 290
      getTableData()
    })

    return {
      ...toRefs(state),
      dialogFormRef,
      confirmPasswordRef,
      getDateTime,
      searchHandle,
      resetHandle,
      handleCurrentChange,
      handleSizeChange,
      settingHandle,
      confirmSuccess,
      selectionChange,
      dialogCancel,
      dialogSave,
      openDialog,
      selectDate,
      uploadSuccess,
    }
  }
}
  </script>
  
  <style lang="scss" scoped>
.f-shopLevel {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 500px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>

<style>
.f-img-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.f-img-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.f-img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 75px;
  height: 75px;
  text-align: center;
}
.f-img {
  width: 75px;
  height: 75px;
}
</style>